import update from 'immutability-helper'
import { setStore, getStore } from 'src/config/mUtils'
import * as types from './action-type';

const defaultState = {
    latitude: '', // 当前位置纬度
    longitude: '', // 当前位置经度
    cartList: {}, // 加入购物车的商品列表
    shopDetail: null, //商家详情信息
    userInfo: null, //用户信息
    shopid: null,//商铺id
    remarkText: null,//可选备注内容
    inputText: '',//输入备注内容
    invoice: false,//开发票
    newAddress: [], //确认订单页新的地址
    searchAddress: null,//搜索并选择的地址
    geohash: null,//地址geohash值
    choosedAddress: null,//选择地址
    addressIndex: null,//选择地址的索引值
    needValidation: null,//确认订单时是否需要验证
    cartId: null, //购物车id
    sig: null,//购物车sig
    orderParam: null,//订单的参数
    orderMessage: null, //订单返回的信息
    orderDetail: null, //订单详情
    login: true,//是否登录
    imgPath: null,//头像地址
    removeAddress: [],//移除地址
    addAddress: '',		//新增地址
    question: null,//问题详情
    cartPrice: null, //会员卡价格
    cityName: '请选择地址...'
}
// 首页表单数据
const reducer = (state = defaultState, action = {}) => {
    switch (action.type) {
        // 记录当前经度纬度
        case types.RECORD_ADDRESS:
            return {
                ...state,
                latitude: action.latitude,
                longitude: action.longitude,
                cityName: action.cityName
            }
        // 记录商品详情
        case types.RECORD_SHOPDETAIL:
            return {
                ...state,
                shopDetail: action.detail
            }
        // 加入购物车
        case types.ADD_CART: {
            let {
                shopid,
                category_id,
                item_id,
                food_id,
                name,
                price,
                specs,
                packing_fee,
                sku_id,
                stock
            } = action;
            let cart = state.cartList;
            let shop = cart[shopid] = (cart[shopid] || {});
            let category = shop[category_id] = (shop[category_id] || {});
            let item = category[item_id] = (category[item_id] || {});
            if (item[food_id]) {
                item[food_id]['num']++;
            } else {
                item[food_id] = {
                    "num": 1,
                    "id": food_id,
                    "name": name,
                    "price": price,
                    "specs": specs,
                    "packing_fee": packing_fee,
                    "sku_id": sku_id,
                    "stock": stock
                };
            }
            //存入localStorage
            setStore('buyCart', { ...cart });
            return update(state, {
                cartList: {
                    $set: { ...cart }
                }
            })
        }
        // 移出购物车
        case types.REDUCE_CART: {
            let { shopid,
                category_id,
                item_id,
                food_id,
                // name,
                // price,
                // specs,
            } = action;
            let cart = state.cartList;
            let shop = (cart[shopid] || {});
            let category = (shop[category_id] || {});
            let item = (category[item_id] || {});
            if (item && item[food_id]) {
                if (item[food_id]['num'] > 0) {
                    item[food_id]['num']--;
                    //存入localStorage
                    setStore('buyCart', { ...cart });
                    return update(state, {
                        cartList: {
                            $set: { ...cart }
                        }
                    })
                } else {
                    //商品数量为0，则清空当前商品的信息
                    item[food_id] = null;
                }
            }
            return state
        }
        //网页初始化时从本地缓存获取购物车数据
        case types.INIT_BUYCART: {
            let initCart = getStore('buyCart');
            if (initCart) {
                return update(state, {
                    cartList: {
                        $set: JSON.parse(initCart)
                    }
                })
            }
            return state
        }
        //清空当前商品的购物车信息
        case types.CLEAR_CART: {
            let newState = update(state, {
                cartList: {
                    [action.shopid]: {
                        $set: null
                    }
                }
            })
            setStore('buyCart', newState.cartList);
            return newState
        }
        // 记录用户信息
        case types.RECORD_USERINFO: {
            let info = action.info;
            setStore('user_id', info.user_id);
            return update(state, {
                $merge: {
                    userInfo: info,
                    login: true,
                }
            })
        }
        //获取用户信息
        case types.GET_USERINFO: {
            let info = action.info;
            if (state.userInfo && (state.userInfo.username !== info.username)) {
                return state;
            };
            if (!state.login) {
                return state;
            }
            if (!info.message) {
                return update(state, {
                    userInfo: {
                        $set: { ...info }
                    }
                })
            } else {
                return update(state, {
                    userInfo: {
                        $set: null
                    }
                })
            }
        }
        //修改用户名
        case types.RETSET_NAME: {
            return update(state, {
                userInfo: {
                    $merge: {
                        username: action.username
                    }
                }
            })
        }
        //保存商铺id
        case types.SAVE_SHOPID: {
            return update(state, {
                shopid: {
                    $set: action.shopid
                }
            })
        }
        //记录订单页面用户选择的备注, 传递给订单确认页面
        case types.CONFIRM_REMARK: {
            let { remarkText, inputText } = action;
            return {
                ...state,
                remarkText,
                inputText
            }
        }
        //是否开发票
        case types.CONFIRM_INVOICE: {
            return {
                ...state,
                invoice: action.invoice
            }
        }
        //选择搜索的地址
        case types.CHOOSE_SEARCH_ADDRESS: {
            return {
                ...state,
                searchAddress: action.place
            }
        }
        //保存geohash
        case types.SAVE_GEOHASH: {
            return {
                ...state,
                geohash: action.geohash
            }
        }

        //确认订单页添加新的的地址
        case types.CONFIRM_ADDRESS: {
            return update(state, {
                newAddress: {
                    $push: [[action.newAddress]]
                }
            })
        }
        //选择的地址
        case types.CHOOSE_ADDRESS: {
            return {
                ...state,
                choosedAddress: action.address,
                addressIndex: action.index
            }
        }
        //保存下单需要验证的返回值
        case types.NEED_VALIDATION: {
            return {
                ...state,
                needValidation: action.needValidation
            }
        }
        //保存下单后购物id 和 sig
        case types.SAVE_CART_ID_SIG: {
            return {
                ...state,
                cart_id: action.cart_id,
                sig: action.sig
            }
        }
        //保存下单参数，用户验证页面调用
        case types.SAVE_ORDER_PARAM: {
            return {
                ...state,
                orderParam: action.orderParam
            }
        }
        //修改下单参数
        case types.CHANGE_ORDER_PARAM: {
            return update(state, {
                orderParam: {
                    $merge: {
                        ...action.newParam
                    }
                }
            })
        }
        //下单成功，保存订单返回信息
        case types.ORDER_SUCCESS: {
            return {
                ...state,
                cartPrice: null,
                orderMessage: action.order
            }
        }
        //进入订单详情页前保存该订单信息
        case types.SAVE_ORDER: {
            return {
                ...state,
                orderDetail: action.orderDetail
            }
        }
        //退出登录
        case types.OUT_LOGIN: {
            return {
                ...state,
                userInfo: {},
                login: false
            }
        }
        //保存图片
        case types.SAVE_AVANDER: {
            return {
                ...state,
                imgPath: action.imgPath
            }
        }
        //删除地址列表
        case types.SAVE_ADDRESS: {
            return {
                ...state,
                removeAddress: action.newAdress
            }
        }
        //添加地址name
        case types.SAVE_ADDDETAIL: {
            return {
                ...state,
                addAddress: action.addAddress
            }
        }
        //保存所选问题标题和详情
        case types.SAVE_QUESTION: {
            return {
                ...state,
                question: action.question
            }
        }
        //增加地址
        case types.ADD_ADDRESS: {
            return update(state, {
                removeAddress: {
                    $unshift: [[action.obj]]
                }
            })
        }
        //会员卡价格纪录
        case types.BUY_CART: {
            return {
                ...state,
                cartPrice: action.price
            }
        }
        default:
            return state;
    }
}

export default reducer